from copy import deepcopy
import numpy as np
from admm.ADMM_update import terminal_args


def upper_grid_update(
    Ct: np.matrix,
    Pmax: float,
    Pmin: float,
    terminal: terminal_args,
    rou: float,
    T: int,
) -> dict:
    # 解析解：直接等于端口所需功率，
    Psub = -1.0 * terminal.P
    # 如果超限则限定在范围内
    Psub[Psub < Pmin] = Pmin
    Psub[Psub > Pmax] = Pmax
    # gather solution and update y and x
    y = {
        "terminal": deepcopy(terminal),
        "Psub": Psub,
        "Qsub": -1.0 * terminal.Q,
        "Cupper": Ct.transpose() @ Psub,
    }
    y["terminal"].P = -1.0 * Psub
    return y


def start():
    T = 36
    T1 = terminal_args(T)
    T1.P = -1.0*(np.random.random((T, 1))*16+6)
    T1.LP = np.random.random((T, 1))
    T1.Q = np.random.random((T, 1))
    T1.LQ = np.random.random((T, 1))
    T1.V2 = np.random.random((T, 1))
    T1.LV2 = np.random.random((T, 1))
    Ct = np.random.random((T, 1))*20+5
    ret = upper_grid_update(Ct,20,8,T1,0.7,T)
    print(f'Pk:{-1.0*T1.P.transpose()}\nPk+1:{ ret["Psub"].transpose() }')
